package net

import (
	"data-system/models"
	"data-system/tools"
	"log"
	"sync"

	"github.com/gorilla/websocket"
)

type Sender struct {
	Id        string
	Conn      *websocket.Conn
	MsgChan   chan models.XMessage
	CloseChan chan struct{}
	Wg        *sync.WaitGroup
}

func NewSender(id string, conn *websocket.Conn, msgChan chan models.XMessage, wg *sync.WaitGroup) *Sender {
	Send := &Sender{
		Id:        id,
		Conn:      conn,
		MsgChan:   msgChan,
		CloseChan: make(chan struct{}),
		Wg:        wg,
	}
	return Send
}

func (s *Sender) Watch() {
	defer s.Wg.Done()
	for {
		select {
		case message, ok := <-s.MsgChan:
			if !ok {
				return // 通道已关闭
			}
			if err := s.Conn.WriteMessage(websocket.TextMessage, []byte(tools.ObjToJson(message))); err != nil {
				log.Println("发送错误:", err)
				close(s.CloseChan)
				return
			}
		case <-s.CloseChan:
			return
		}
	}
}
